﻿using System;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace KL.UFrame.Core.Authorization
{
    /// <summary>
    /// 认证类
    /// </summary>
    public class K9AuthorizeAttribute : AuthorizeAttribute
    {
        #region 重载

        /// <summary>
        /// 当前Action对应的角色列表
        /// </summary>
        public new string[] Roles { get; set; }

        /// <summary>
        /// 开始认证
        /// </summary>
        /// <param name="actionContext"></param>
        public override void OnAuthorization(HttpActionContext actionContext)
        {
            var controllerName = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName.ToLower();
            var actionName = actionContext.ActionDescriptor.ActionName.ToLower();

            GetActionRoles(actionName, controllerName);

            base.OnAuthorization(actionContext);
        }

        /// <summary>
        /// 判断权限
        /// </summary>
        /// <param name="actionContext"></param>
        /// <returns></returns>
        protected override bool IsAuthorized(HttpActionContext actionContext)
        {
            if (actionContext == null)
            {
                throw new ArgumentNullException(nameof(actionContext));
            }

            //已经标记为 {AllowAnonymous]
            if (actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any()) return true;

            //不限制用户，仅限制客户端
            if (Roles == null)
            {
                return base.IsAuthorized(actionContext);
            }

            //没有角色限制，只限制是否登录
            if (Roles.Length == 0)
            {
                return actionContext.RequestContext.Principal.Identity.IsAuthenticated 
                    && !string.IsNullOrEmpty(actionContext.RequestContext.Principal.Identity.Name);
            }

            //限制角色
            if (Roles.Any(actionContext.RequestContext.Principal.IsInRole))
            {
                return true; ;
            }
            
            //允许管理员访问
            return actionContext.RequestContext.Principal.IsInRole("Admin");
        }

        /// <summary>
        /// 认证失败
        /// </summary>
        /// <param name="actionContext"></param>
        protected override void HandleUnauthorizedRequest(HttpActionContext actionContext)
        {
            var response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized);
            response.Content = new StringContent("{\"Code\":-401,\"Message\":\"当前用户没有访问权限\"}", Encoding.UTF8,
                "application/json");
            actionContext.Response = response;
        }
        #endregion

        #region 私有方法

        /// <summary>
        /// 查询当前页面对应的角色 
        /// </summary>
        /// <param name="actionName"></param>
        /// <param name="controllerName"></param>
        private void GetActionRoles(string actionName, string controllerName)
        {
            //从缓存或者数据库中读取action的授权角色列表，赋值到Roles
            if (controllerName == "account") Roles = new string[] { };
        }

        #endregion
    }
}